package com.hd.util;

import com.hd.entity.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@CrossOrigin  //跨域
public class UploadUtil {
    //单独上传图片，把上传后的图片名称返回给前端
    @RequestMapping("/upload")
    public Object uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        String fname = file.getOriginalFilename();
        if(fname.contains("/")){
            fname = fname.substring(fname.lastIndexOf("/")+1);
        }
        fname = UUID.randomUUID().toString() + fname;
        String img = request.getRealPath("img");
        System.out.println(img.toString());
        file.transferTo(new File(img, fname));
        return new Result(200,fname,null);
    }
//    图片的预览
    @RequestMapping("/showimg")
    public void showimg(String filename, HttpServletResponse response, HttpServletRequest request)throws Exception{
        String img = request.getRealPath("img");
        File file = new File(img, filename);
        FileInputStream fis = new FileInputStream(file);
        response.setHeader("Content-Disposition", "filename=" + filename);
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(fis, os);
        os.close();
        fis.close();
    }

}
